package com.jch.dm8_thread_specific_storage.example.tomcat.demo.memoryleaking;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.atomic.AtomicInteger;

// ThreadLocal伪内存泄漏示例代码
public class MemoryPseudoLeakingServlet extends HttpServlet {

    private final static ThreadLocal<AtomicInteger> TL_COUNTER = new ThreadLocal<AtomicInteger>() {
        @Override
        protected AtomicInteger initialValue() {
            return new AtomicInteger();
        }
    };

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter pwr = resp.getWriter();
        pwr.write(String.valueOf(TL_COUNTER.get().getAndIncrement()));
        pwr.close();
    }

    // 在服务器环境下使用ThreadLocal导致内存泄漏的关键条件：
    // Web应用程序的类加载器持有对ThreadLocal实例的可达引用。
}
